package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import common.RowMapper;
import common.SQLTemplate;
import pojo.Policy;
import pojo.Right;
import dao.RightDAO;

public class RightDAOImpl extends BaseDAO implements RightDAO {

	@Override
	public Right getRightsOfOperatorId(String operatorId) {
		String sql = SQLTemplate.RIGHT_SELECT_JOIN_OPERATOR_SQL
				+ "AND OPERATOR_ID='" + operatorId + "';";
		Right rights = null;
		try {
			rights = (Right) queryForObject(sql,
					new RightRowMapper());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rights;
	}

	@Override
	public List<Right> getOperatorsRightsList() {
		String sql = SQLTemplate.RIGHT_SELECT_JOIN_OPERATOR_SQL+ ";";
		List<Right> rightsList = null;
		try {
			rightsList = (List<Right>) queryForList(sql,
					new RightRowMapper());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rightsList;
	}

	@Override
	public Right updateRightsOfOperatorId(Right right) {
		String tableName = "T_RIGHT";
		String[] columnNames = { "RIGHTS"};
		String[] values = { right.getRights()};
		String sql = SQLTemplate.updateSQLTemplate(tableName, columnNames,
				values) + "WHERE OPERATOR_ID='" + right.getOperatorId();
		try {
			update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return right;
	}
	private class RightRowMapper implements RowMapper<Object> {
		private RightRowMapper() {
		}

		public Right mapRow(ResultSet rs, int rowNum) throws SQLException {
			String id = rs.getString("id");
			String rights = rs.getString("rights");
			String operatorId = rs.getString("operator_id");
			String operatorName = rs.getString("operator_name");
			Right right = new Right();
			if (id != null) {
				right.setId(id);
			}
			if (rights != null) {
				right.setRights(rights);
			}
			if (operatorId != null) {
				right.setOperatorId(operatorId);
			}
			if (operatorName != null) {
				right.setOperatorName(operatorName);
			}
			return right;
		}
	}
}
